package vtt.android.lichphatsongbongda.fragments;

import java.net.URI;
import java.util.List;

import vtt.android.library.utils.VttUtils;
import vtt.android.library.utils.api_helper.HTTPRequestor;
import vtt.android.library.utils.api_helper.HTTPRequestor.Listener;
import vtt.android.lichphatsongbongda.R;
import vtt.android.lichphatsongbongda.activities.LichPhatSongActivity;
import vtt.android.lichphatsongbongda.adapters.TVScheduleAdapter;
import vtt.android.lichphatsongbongda.database.TVScheduleDAO;
import vtt.android.lichphatsongbongda.dialogs.DialogManager;
import vtt.android.lichphatsongbongda.entities.TVScheduleItem;
import vtt.android.lichphatsongbongda.entities.TVScheduleResult;
import vtt.android.lichphatsongbongda.utils.CommonUtils;
import vtt.android.lichphatsongbongda.utils.TVScheduleAPI;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.android.gms.ads.AdView;
import com.twotoasters.jazzylistview.JazzyListView;

/**
 * A placeholder fragment containing a simple view.
 */
@SuppressLint("SimpleDateFormat")
public class TVScheduleFragment extends BaseFragment {
	
	/* define constant */
	public static final String PREF_HOUR = "current_hour";
	private static final String ARG_SECTION_NUMBER = "section_number";
	
	private View mLPSRootView;
	private TVScheduleDAO tvScheduleDB;
	
	private SharedPreferences mSharePref;
    private LichPhatSongActivity mParentAct;
	private JazzyListView mListView;
	private View mProgressBar;
	
	/**
	 * Returns a new instance of this fragment for the given section number.
	 */
	public static TVScheduleFragment newInstance(int sectionNumber) {
		TVScheduleFragment fragment = new TVScheduleFragment();
		Bundle args = new Bundle();
		args.putInt(ARG_SECTION_NUMBER, sectionNumber);
		fragment.setArguments(args);
		return fragment;
	}
	
	@Override
	public void onAttach(Activity activity) {
	    super.onAttach(activity);
	    mParentAct = (LichPhatSongActivity) activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mSharePref = CommonUtils.getSharedPreferences(mParentAct);
		tvScheduleDB = TVScheduleDAO.getInstance(mParentAct);
		tvScheduleDB.open();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		mLPSRootView = inflater.inflate(R.layout.fragment_lich_phat_song, container, false);

		// Look up the AdView as a resource and load a request.
		AdView adView = (AdView) mLPSRootView.findViewById(R.id.adView);
		// load admob
		loadAdmob(adView);
				
		mListView = (JazzyListView) mLPSRootView.findViewById(R.id.lv_tivi_schedule);
		mProgressBar = mLPSRootView.findViewById(R.id.progressBar1);
		
		getDataFromDB(); 
		// load page
		reloadPage();

		return mLPSRootView;
	}

	/**
	 * 
	 */
	private void getDataFromDB() {
		List<TVScheduleItem> tvScheduleList = tvScheduleDB.loadCacheData();
		// load from local first
        if(tvScheduleList.size() > 0) {
            TVScheduleAdapter adapter = new TVScheduleAdapter(mParentAct, tvScheduleList);
            mListView.setAdapter(adapter);
        }
	}
	
    private void reloadPage() {
        
		// if data is not expired, then return
		if (!isLpsDataExpired()) {
			return;
		}

		if (!VttUtils.checkNetworkConnection(mParentAct)) {
			mDialogManager.showCommonDialog(
					DialogManager.DIALOG_TYPE_INFOR, 
					getString(R.string.msg_title_notice),
					getString(R.string.msg_network_error), null);
			return;
		}

    	TVScheduleAPI requestApi = new TVScheduleAPI(mParentAct);
    	mProgressBar.setVisibility(View.VISIBLE);
    	requestApi.getSchedule(new HTTPRequestor(new Listener() {
			
			@Override
			public void onSucceed(HTTPRequestor requestor, URI uri, Object content) {
				log.d("VTT>>> onSucceed");
				
				mProgressBar.setVisibility(View.GONE);
				TVScheduleResult result = (TVScheduleResult) content;
				if(result != null) {
					List<TVScheduleItem> tvScheduleList = result.getTvScheduleList();
					// save data into DB
					saveData(tvScheduleList);
					// reload new data from DB
					getDataFromDB();
				}
			}
			
			@Override
			public void onFailed(HTTPRequestor requestor, URI uri, Throwable throwable) {
				log.e("VTT>>> onFailed");
				if(getActivity() == null) {
					return;
				}
				mProgressBar.setVisibility(View.GONE);
				Toast.makeText(mParentAct, "Không lấy được dữ liệu mới, vui lòng thử lại!", 0).show();
				getDataFromDB();
			}
		}));
    	
    }
    
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
        inflater.inflate(R.menu.menu_kenhtv, menu);
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		log.d("VTT>>> action_refresh" + "");
		switch (item.getItemId()) {
		case R.id.action_watch_tv:
		    // open page watch TV
		    ((LichPhatSongActivity)mParentAct).openPageTV();
		    return true;
		case R.id.action_refresh:
			mSharePref.edit().putLong(TVScheduleFragment.PREF_HOUR, -1).commit();
			reloadPage();
			return true;
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	// save LPS cache data
	private void saveData(List<TVScheduleItem> tvSchedules){
        tvScheduleDB.saveCacheData(tvSchedules);
        long hour = System.currentTimeMillis() / 1000 / 60 / 60;
        mSharePref.edit().putLong(PREF_HOUR, hour).commit();
    }
    
    /**
     * get LPS cache data every 1 hour
     * @return boolean
     */
    private boolean isLpsDataExpired(){
        long curHour = System.currentTimeMillis() / 1000 / 60 / 60;
        long oldHour = mSharePref.getLong(PREF_HOUR, -1);
         
        // if current hour > old hour thi se kiem tra lay data trong db
        if(oldHour == -1 || (curHour - oldHour) > 0){
            log.d("VTT>>> data expired ");
            return true;
        }
        log.d("VTT>>> data up to date ");
        
        return false;
    }
}